package com.woniuxy.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;

import com.woniuxy.entity.HospitalMeta;
import com.woniuxy.service.IHospitalService;
import com.woniuxy.util.InitDBUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：xurice
 * @date：Created in 2024/4/22 15:23
 * @description：数据源配置类
 * @modified By：
 * @version: $
 */

@Component
public class DynamicDatasourceConfig {

    private Map<String,String> hospitalTable= new HashMap<>();

    @Autowired
    private IHospitalService hospitalService;
    @Autowired
    private DynamicRoutingDataSource dataSource;


    @PostConstruct
    public void loadAllDB(){
        hospitalTable.put("master","管理中心");
        List<HospitalMeta> hospitalMetas = hospitalService.selectAvailable(new HospitalMeta());
        for (HospitalMeta hospitalMeta : hospitalMetas) {
            DruidDataSource db = InitDBUtil.getInitDb();
            db.setUsername(hospitalMeta.getMysqlUsername());
            db.setPassword(hospitalMeta.getMysqlPassword());
            db.setUrl("jdbc:mysql://"+hospitalMeta.getMysqlUrl()+"/"+hospitalMeta.getMysqlSchema()+"?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowMultiQueries=true");
            dataSource.addDataSource(hospitalMeta.getMysqlSchema(),db);
            hospitalTable.put(hospitalMeta.getMysqlSchema(),hospitalMeta.getHospitalName());
        }
    }

    public void addDb(HospitalMeta hospitalMeta){
        DruidDataSource db = InitDBUtil.getInitDb();
        db.setUsername(hospitalMeta.getMysqlUsername());
        db.setPassword(hospitalMeta.getMysqlPassword());
        db.setUrl("jdbc:mysql://"+hospitalMeta.getMysqlUrl()+"/"+hospitalMeta.getMysqlSchema()+"?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowMultiQueries=true");
        dataSource.addDataSource(hospitalMeta.getMysqlSchema(),db);
        hospitalTable.put(hospitalMeta.getMysqlSchema(),hospitalMeta.getHospitalName());
    }

    public String getHospitalBySchema(String schema){
        return hospitalTable.containsKey(schema)?hospitalTable.get(schema):"";
    }
}
